<template>
  <el-button
    :circle="true"
    :disabled="state.value !== 0 || props.disable"
    class="count-down"
    style="border-radius: 2px !important"
    @click="getCodeHandler"
  >
    <span v-if="state.value === 0">获取验证码</span>
    <span v-else style="color: #010205">{{ state.value + 's' }}</span>
  </el-button>
</template>
<script setup>
  import { reactive } from 'vue';
  const props = defineProps({
    disable: {
      type: Boolean,
      required: true,
      default: true,
    },
  });
  const state = reactive({
    value: 0,
    timer: null,
    maxValue: 60,
  });
  const emits = defineEmits(['send-code']);
  defineExpose({
    resetart,
    reset,
  });

  function resetart() {
    state.value = state.maxValue;
    go();
  }
  function go() {
    clearInterval(state.timer);
    state.timer = setInterval(() => {
      state.value--;
      if (state.value === 0) {
        clearInterval(state.timer);
      }
    }, 1000);
  }
  function stop() {
    clearInterval(state.timer);
  }

  function reset() {
    clearInterval(state.timer);
    state.value = 0;
  }

  function getCodeHandler() {
    emits('send-code');
  }

  onUnmounted(() => {
    stop();
  });
</script>
<style scoped lang="scss">
  .count-down {
    width: 106px;
    height: 50px;
    .el-button.is-disabled {
      color: red !important;
    }
  }
</style>
